package com.bsoft.gol.hbs.dao;

import ctd.dictionary.DictionaryItem;
import ctd.mixin.dictionary.DBDictionaryItemLoader;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import hcn.base.Product;
import org.hibernate.Query;
import org.hibernate.StatelessSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liuxj on 2016/8/1.
 */
public abstract class ProductDAO extends HibernateSupportDelegateDAO<Product> implements DBDictionaryItemLoader<Product> {
    public ProductDAO() {
        this.setKeyField("productId");
    }

    /**
     * 产品列表
     * @return
     */
    @DAOMethod(sql = "from Product where status='1'")
    public abstract List<Product> queryProductsInfo();


    /**
     * 产品信息-根据产品Id明细信息
     *
     * @param productId
     * @return
     */
    @DAOMethod(sql = "from Product where productId =:productId and status='1'")
    public abstract Product getProductDetailById(@DAOParam("productId") int productId);

    /**
     * 产品信息-根据产品编码查询（新增的判断）
     * @param productCode
     * @return
     */
    @DAOMethod(sql = "from Product where productCode =:productCode and status='1'")
    public abstract Product getProductByCodeForInsert(@DAOParam("productCode") String productCode);

    /**
     * 产品信息-根据产品编码查询（修改的判断）
     * @param productCode
     * @param productId
     * @return
     */
    @DAOMethod(sql = "from Product where productCode =:productCode and productId<>:productId and status='1'")
    public abstract Product getProductByCodeForUpdate(@DAOParam("productCode") String productCode,
                                                      @DAOParam("productId") int productId);

    /**
     * 逻辑删除
     * @param productId
     */
    @DAOMethod(sql = "update Product set status='0',lastModify=Now() where productId=:productId")
    public abstract void delete(@DAOParam("productId") int productId);
    
    /**
     * 更新
     */
    public int updateProduct(final Product product) {
        HibernateStatelessResultAction<Integer> action = new AbstractHibernateStatelessResultAction<Integer>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query query = ss.createQuery("update Product set productCode=:productCode,productName=:productName,description=:description,status=:status,lastModify=:lastModify,Modifier=:Modifier where productID=:productID");
                query.setParameter("productCode", product.getProductCode());
                query.setParameter("productName", product.getProductName());
                query.setParameter("description", product.getDescription());
                query.setParameter("status", product.getStatus());
                query.setParameter("lastModify", product.getLastModify());
                query.setParameter("Modifier", product.getModifier());
                query.setParameter("productID", product.getProductId());
                Integer flag = query.executeUpdate();
                setResult(flag);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 字典
     */
    @Override
    public List<DictionaryItem> findAllDictionaryItem(final int start, final int limit) {
        HibernateStatelessResultAction<List<DictionaryItem>> action = new AbstractHibernateStatelessResultAction<List<DictionaryItem>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query sqlQuery = ss.createQuery("from Product where status='1'");
                sqlQuery.setFirstResult(start);
                sqlQuery.setMaxResults(limit);
                List<Product> ds = sqlQuery.list();
                List<DictionaryItem> dis = new ArrayList<DictionaryItem>();
                for (Product d : ds) {
                    int key = d.getProductId();
                    String text = d.getProductName();
                    Map<String, Object> properties = ConversionUtils.convert(d, Map.class);
                    properties.remove("productId");
                    properties.remove("productName");
                    DictionaryItem di = new DictionaryItem(key, text, properties);
                    dis.add(di);
                }
                setResult(dis);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    @Override
    public DictionaryItem getDictionaryItem(final Object key) {
        HibernateStatelessResultAction<DictionaryItem> action = new AbstractHibernateStatelessResultAction<DictionaryItem>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query sqlQuery = ss.createQuery("from Product where productId=:productId");
                sqlQuery.setParameter("productId", key);
                List<Product> rs = sqlQuery.list();
                if (rs.size() > 0) {
                    Product d = rs.get(0);
                    int key = d.getProductId();
                    String text = d.getProductName();
                    Map<String, Object> properties = ConversionUtils.convert(d, Map.class);
                    DictionaryItem di = new DictionaryItem(key, text, properties);
                    setResult(di);
                } else {
                    setResult(null);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

}
